package com.atwisdom.star.core.bsl.business.utils;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class RestTemplateUtil {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${erp.erpUri}")
    private String erpUri;

    @Value("${erp.tranType}")
    private String tranType;

    @Value("${erp.system}")
    private String system;

    @Value("${erp.userCode}")
    private String userCode;

    @Value("${erp.password}")
    private String password;

    /**
     * @param serviceName
     * @param params
     * @param mediaType
     * @return
     * @Title: post
     * @Description: 将参数都拼接在url之后
     * @return: String
     */
    public JSONObject post(String serviceName, JSONObject params, MediaType mediaType) {
        String url = erpUri+serviceName;
        // 拿到header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(mediaType);
        requestHeaders.add(ConstantInfo.TRAN_TYPE, tranType);
        requestHeaders.add(ConstantInfo.SYSTEM, system);
        requestHeaders.add(ConstantInfo.USER_CODE, userCode);
        requestHeaders.add(ConstantInfo.PASSWORD, password);
        HttpEntity<JSONObject> requestEntity = (mediaType == MediaType.APPLICATION_JSON
                || mediaType == MediaType.APPLICATION_JSON_UTF8) ? new HttpEntity<>(params, requestHeaders)
                : new HttpEntity<>(null, requestHeaders);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        JSONObject result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8)
                ? restTemplate.postForObject(url, requestEntity, JSONObject.class)
                : restTemplate.postForObject(expandURL(url, params.keySet()), requestEntity, JSONObject.class, params);
        return result;
    }

    /**
     * @param url
     * @param keys
     * @return: String
     */
    private static String expandURL(String url, Set<?> keys) {
        final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
        Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
        StringBuilder sb = new StringBuilder(url);
        if (mc.find()) {
            sb.append("&");
        } else {
            sb.append("?");
        }

        for (Object key : keys) {
            sb.append(key).append("=").append("{").append(key).append("}").append("&");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

}
